#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 简单定位图片

import sys
import os
sys.path.append('/usr/local/lib/python2.7/site-packages/')
import cv2
import numpy as np
from matplotlib import pyplot as plt  

def showpiclocation(img, findimg):
    # 定位图片
    w = img.shape[1]
    h = img.shape[0]
    fw = findimg.shape[1]
    fh = findimg.shape[0]
    findpt = None
    for now_h in xrange(0, h - fh):
        for now_w in xrange(0, w - fw):
            comp_tz = img[now_h:now_h + fh, now_w:now_w + fw, :] - findimg
            if abs(np.mean(comp_tz)) < 20:
                findpt = now_w, now_h
                print "ok"
        print ".",
    if findpt != None:
        cv2.rectangle(
            img, findpt, (findpt[0] + fw, findpt[1] + fh), (0, 0, 255))
    return img


fn = os.path.dirname(os.path.realpath(__file__)) + '/b.png'
fn1 = os.path.dirname(os.path.realpath(__file__)) + '/a.png'
myimg = cv2.imread(fn)
# myimg = cv2.cvtColor(myimg, cv2.COLOR_BGR2GRAY)
img2 = myimg.copy() 
myimg1 = cv2.imread(fn1)
# myimg1 = cv2.cvtColor(myimg1, cv2.COLOR_BGR2GRAY)
myimg1=myimg1[20:107, 20:107]
b,w, h = myimg1.shape[::-1]
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',  
           'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
    method = eval(meth)
    img = img2.copy()
    res = cv2.matchTemplate(img, myimg1, method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv2.rectangle(img, top_left, bottom_right, 255, 2)
    print meth
    plt.subplot(221), plt.imshow(img2,cmap= "gray")  
    plt.title('WeChat'), plt.xticks([]),plt.yticks([])  
    # plt.subplot(222), plt.imshow(myimg1,cmap= "gray")  
    # plt.title('template Image'),plt.xticks([]),plt.yticks([])  
    # plt.subplot(223), plt.imshow(res,cmap= "gray")  
    # plt.title('Matching Result'), plt.xticks([]),plt.yticks([])  
    plt.subplot(224), plt.imshow(img,cmap= "gray")  
    plt.title('Image'),plt.xticks([]),plt.yticks([])  
    plt.show()  
# myimg = showpiclocation(myimg, myimg1)
# cv2.namedWindow('img')
# cv2.imshow('img', myimg)
# cv2.waitKey()
# cv2.destroyAllWindows()
